resource "alicloud_vpc" "vpc" {
  count             = var.vpc_id != "" ? 0 : var.create ? 1 : 0
  vpc_name          = var.vpc_name
  cidr_block        = var.vpc_cidr
  resource_group_id = var.resource_group_id
  description       = var.vpc_description
  tags = merge(
  {
    "Name" = format("%s", var.vpc_name)
  },
  var.vpc_tags
  )
}

resource "alicloud_vswitch" "main" {
  count      = length(var.vswitch_cidrs)
  vpc_id     = var.vpc_id != "" ? var.vpc_id : concat(alicloud_vpc.vpc.*.id, [""])[0]
  vswitch_name = format("%s-%01d", var.vswitch_name, count.index + 1)

  cidr_block = element(var.vswitch_cidrs, count.index)
  zone_id    = element(var.availability_zones, count.index)

  tags = merge(
  {
    "Name" = format("%s-%01d", var.vswitch_name, count.index+1)
  },
  var.vswitch_tags
  )

  depends_on = [alicloud_vpc.vpc]
}

resource "alicloud_nat_gateway" "main" {
  count      = var.enabled_nat_gateway ? 1 : 0
  vpc_id     = var.vpc_id != "" ? var.vpc_id : concat(alicloud_vpc.vpc.*.id, [""])[0]
  name       = var.nat_gateway_name
  vswitch_id = alicloud_vswitch.main[0].id
  nat_type   = "Enhanced"
  tags       = merge(
    {
      "Name" = format("%s-%01d", var.nat_gateway_name, count.index+1)
    },
    var.nat_gateway_tags
  )
}

resource "alicloud_eip_address" "main" {
  count                = var.enabled_nat_gateway ? 1 : 0
  address_name         = "${var.nat_gateway_name}-snat"
  isp                  = "BGP"
  internet_charge_type = "PayByTraffic"
  bandwidth            = 200
  tags                 = merge(
    {
      "Name" = format("%s", var.nat_gateway_name)
    },
    var.nat_gateway_tags
  )
}

resource "alicloud_eip_association" "default" {
  count         = var.enabled_nat_gateway ? 1 : 0
  allocation_id = alicloud_eip_address.main[0].id
  instance_id   = alicloud_nat_gateway.main[0].id

  depends_on    = [alicloud_eip_address.main, alicloud_nat_gateway.main]
}

resource "alicloud_snat_entry" "default" {
  count             = var.enabled_nat_gateway && length(var.vswitch_cidrs) > 0 ? length(var.vswitch_cidrs) : 0
  snat_table_id     = alicloud_nat_gateway.main[0].snat_table_ids
  source_vswitch_id = alicloud_vswitch.main[count.index].id
  snat_ip           = alicloud_eip_address.main[0].ip_address

  depends_on        = [alicloud_eip_association.default]
}
